<?php


namespace App\Services\Game;


use App\DTOS\Admin\PayOrderInsertDTO;
use App\DTOS\NeiGouDTO;
use App\DTOS\QzlOrderDTO;
use App\Exceptions\ServiceException;
use App\Models\Game\GameGoods;
use App\Models\Game\PayOrder;
use App\Models\Game\Server;
use App\Utils\ResponseUtil;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use SimpleSoftwareIO\QrCode\Facades\QrCode;

class QzlService
{

    private NeigouService $NeigouService;
    private PayOrderService $payOrderService;
    private UserRoleService $userRoleService;
    private UserMemberService $userMemberService;

    /**
     * PayOrderService constructor.
     * @param NeigouService $NeigouService
     * @param PayOrderService $payOrderService
     * @param UserRoleService $userRoleService
     * @param UserMemberService $userMemberService
     */
    public function __construct(NeigouService $NeigouService,PayOrderService $payOrderService,UserRoleService $userRoleService, UserMemberService $userMemberService)
    {
        $this->NeigouService = $NeigouService;
        $this->payOrderService = $payOrderService;
        $this->userRoleService = $userRoleService;
        $this->userMemberService = $userMemberService;
    }

    /** 趣智连验签
     * @param string $params
     * @param $appkey
     * @return bool
     */
    public function verification($params, $appkey) {
        $data = json_decode($params,true);
        $sign0 = data_get($data,'sign');
        unset($data['sign']);
        $sign1 = $this->getSign($data,$appkey);
        return $sign0 === $sign1;
    }

    /**
     * 趣智连 签名计算
     * @param array $params
     * @param string $app_secret
     * @return string
     */
    public function getSign($params,$app_secret) {
        $extra = $params['extra'] ?? null;
        if($extra) {
            unset($params['extra']);
            foreach($extra as $key=>$val){
                $params[$key] = $val;
            }
        }
        ksort($params);
        $stringToBeSigned = "";
        foreach ($params as $k => $v) {
            if(strlen($v) > 0) {
                $stringToBeSigned .= "$k=$v&";
            }
        }
        $stringToBeSigned = substr($stringToBeSigned, 0, -1);
        $stringToBeSigned .= "&paySecret=".$app_secret;
        return strtoupper(md5($stringToBeSigned));
    }

    /**
     * @param PayOrder $payOrder
     * @return bool
     * @throws ServiceException
     */
    public function query(PayOrder $payOrder) //趣智联主动查询
    {
        $requestData = [
            'tradeType'=>'cs.order.query',
            'version'=>'2.0',
            'mchNo'=>config('app.qzl_mchNo'),
            'mchOrderNo'=>$payOrder->order_no
        ];
        $sign = $this->getSign($requestData,config('app.qzl_secret'));
        $requestData['sign'] = $sign;

        $result = httpPost(config('app.qzl_url') , dataToParams($requestData));
        // error : {"errCode":"mchOrderNoUsed","resultCode":1,"errMsg":"订单号不存在:订单号不存在","message":"","mchNo":"M8822023120810000358","status":0}
        // success: {"cpOrderNo":"358qzl_522357570241957888","payResult":"WAITING_PAYMENT","amount":"1","mchOrderNo":"qzl_522357570241957888","resultCode":0,"errMsg":"","sign":"CEF3A6F61C9E85E497FD200F919795BB","message":"1013202312120000009116331290","mchNo":"M8822023120810000358","status":0}
        $responseData = json_decode($result,true);
        $resultCode = data_get($responseData,'resultCode');
        if($resultCode == 0){
            $payResult = data_get($responseData,'payResult');
            if($payResult=='SUCCESS'){ //订单支付成功
                if ($payOrder->status !=1 ) {
                    $payOrder->updated_at = date("Y-m-d H:i:s");
                    $payOrder->status = 1;
                    $payOrder->save();

                    $goodsId = data_get($payOrder,'goods_id');
                    $gameGoods = GameGoods::query()->find($goodsId);
                    $typeValue = data_get($gameGoods,'type_value');

                    $neiGouDTO = new NeiGouDTO();
                    $neiGouDTO->setGameArea($payOrder->game_area);
                    $neiGouDTO->setNumber($payOrder->number);
                    $neiGouDTO->setRoleId($payOrder->role_id);
                    $neiGouDTO->setOrderNo($payOrder->order_no);
                    $neiGouDTO->setGoodsId($payOrder->goods_id);
                    $neiGouDTO->setTypeValue($typeValue);
                    try {
                        $this->NeigouService->pushToServer($neiGouDTO);
                        $payOrder->updated_at = date("Y-m-d H:i:s");
                        $payOrder->push_status = 1;
                        $payOrder->save();
                    } catch (ServiceException $e) {
                        Log::error("push error: " . $e->getMessage());
                    }
                    return true;
                }
                return true;
            }
            switch($payResult){
                case 'WAITING_PAYMENT': throw new ServiceException('等待支付');
                case 'FAILED': throw new ServiceException('支付失败');
                case 'REFUNDED': throw new ServiceException('退款成功');
                case 'PROCESSING': throw new ServiceException('退款处理中');
                case 'FAILREFUND': throw new ServiceException('退款失败');
            }
        }
        throw new ServiceException('查询失败');
    }

}
